<?php

soc_add_function('work',     'soc_template');

$soc['status'] = '404 Not Found';
if ( is_owner() ) {
    file_put_contents($soc['dir'].'/debug.txt', "Owner.\n", FILE_APPEND);

    if ( is_file("{$soc['dir']}/.posts{$soc['url']['path']}") ) {
        /* Request private file */
        $soc['status'] = '200 FILE';
    } elseif ( $soc['url']['path'] === '/api/' ) {
        /* User API call */
        file_put_contents($soc['dir'].'/debug.txt', 'User API call: '.$_POST['fn']."\n", FILE_APPEND);
        soc_add_function('api', 'user_api');
    } elseif ( preg_match( '/^\/edit\//', $soc['url']['path'] ) ) {
        $soc['status'] = '200 OK';
        $soc['page']   = 'edit.php';
    } elseif ( $soc['url']['path'] === '/config/' ) {
        $soc['status'] = '200 OK';
        $soc['page']   = 'config.php';
    } elseif ( $soc['url']['path'] === '/' ) {
        $soc['status'] = '200 OK';
        $soc['page']   = 'index.php';
    } elseif ( preg_match( '/^\/\d\d\d\d\/\d\d\/\d\d\/\d\d\/\d\d\/$/', $soc['url']['path'] ) ) {
        $json_path = $soc['dir'].'/.posts'.$soc['url']['path'].'index.json';
        if ( is_file( $json_path ) ) {
            global $json;
            $json = json_decode( file_get_contents( $json_path ), true );
            $soc['status'] = '200 OK';
            $soc['page']   = 'post.php';
        }
    }

} else {
    file_put_contents($soc['dir'].'/debug.txt', "Public.\n", FILE_APPEND);

    if ( is_file("{$soc['dir']}/.posts{$soc['url']['path']}") ) {
        /* Request public file */
        $json_path = $soc['dir'].'/.posts'.dirname( $soc['url']['path'] ).'/index.json';
        if ( is_file( $json_path ) ) {
            $json = json_decode( file_get_contents( $json_path ), true );
            if ( $json['public'] === 'true' ) {
                $soc['status'] = '200 FILE';
            }
        }
    } elseif ( $soc['url']['path'] === '/api/' ) {
        /* Public API call */
        soc_add_function('api', 'public_api');
    } elseif ( empty( $config['login_url'] ) && $soc['url']['path'] === '/' ) {
        /* Install */
        $soc['status'] = '200 OK';
        $soc['page']   = 'install.php';
        $config['tpl']     = 'default';
    } elseif ( $config['login_url'] === $soc['url']['path'] ) {
        /* Login */
        $soc['status'] = '200 OK';
        $soc['page']    = 'login.php';
    } elseif ( $soc['url']['path'] === '/' ) {
        $soc['status'] = '200 OK';
        $soc['page']    = 'index.php';
    } elseif ( preg_match( '/^\/\d\d\d\d\/\d\d\/\d\d\/\d\d\/\d\d\/$/', $soc['url']['path'] ) ) {
        $json_path = $soc['dir'].'/.posts'.$soc['url']['path'].'index.json';
        if ( is_file( $json_path ) ) {
            global $json;
            $json = json_decode( file_get_contents( $json_path ), true );
            if ( $json['public'] === 'true' ) {
                $soc['status'] = '200 OK';
                $soc['page']   = 'post.php';
            }
        }
    }

}






/* Шаблонизация или отправка файла из закрытой области */

function soc_template() {
    global $config, $soc, $translate, $json;

    /* Echo file from private zone */
    if ( $soc['status'] === '200 FILE' ) {
        soc_readfile("{$soc['dir']}/.posts{$soc['url']['path']}");
        exit;
    }

    $output = '';
    if ( $soc['status'] === '200 OK' ) {
        ob_start();
        include( "{$soc['dir']}/tpl/{$config['tpl']}/{$soc['page']}" );
        $output = ob_get_clean();
    }
    header($_SERVER["SERVER_PROTOCOL"]." ".$soc['status']);
    echo $output;

}


/* User API */

function user_api() {

    global $config, $soc;

    switch ( $_POST['fn'] ) {

        case 'save_password':
            $config['login_url'] = $soc['base_url'].trim($_POST['login_url']);
            $config['password']  = trim($_POST['password']);
            if ( soc_save_config() ) {
                exit( json_encode( array(
                    'info_text'  => __("Saved"),
                    'info_class' => 'info-success',
                    'info_time'  => 5000,
                ) ) );
            }
        break;

    /* Загрузка аватарки */

        case 'upload_my_ava':
            $mess = __('Error upload file');
            if ( $_FILES['myfile']['error'] == 0 ) {
                if ( move_uploaded_file( $_FILES['myfile']['tmp_name'], "{$soc['dir']}/img/{$_FILES['myfile']['name']}" ) ) {
                    $config['avatar'] = '/img/'.$_FILES['myfile']['name'];
                    soc_save_config();
                    exit( json_encode( array(
                        'info_text'  => __('Files uploaded'),
                        'info_class' => 'info-success',
                        'info_time'  => 3000,
                        'img'        => "<img src='{$config['avatar']}'>",
                    ) ) );
                } else {
                    $mess = __('Error move file');
                }
            }
            exit( json_encode( array(
                'info_text'  => $mess,
                'info_class' => 'info-error',
                'info_time'  => 3000,
            ) ) );
        break;

    /* Загрузка файлов */

        case 'upload_files':

        /* Сгенерировать адрес если не передан в запросе */

            $time    = time();
            $url = date( '/Y/m/d/H/i/', $time );
            if ( !empty( $_POST['url'] ) ) {
                $url = $_POST['url'];
            }
            $dir = $soc['dir'].'/.posts'.$url;
            
        /* Предотвратить перезапись если пост создается в ту же минуту */

            if ( is_dir( $dir ) && empty( $_POST['url'] ) ) {
                exit( json_encode( array(
                    'info_text'  => __('Please wait 1 min. Files were not uploaded.'),
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) );
            }

        /* Создание папки если не существует */

            if ( !is_dir( $dir ) && !mkdir( $dir, 0777, true ) ) {
                exit( json_encode( array(
                    'info_text'  => __('Can\'t create folder').' '.$dir,
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) );
            }


            $flist = array();
            $success = true;
            foreach ( $_FILES['myfile']['name'] as $n => $name ) {
                if ( $_FILES['myfile']['error'][$n] ) {
                    $success = false;
                    $text = __('Error upload file').' '.$name;
                    break;
                }
                $uploaded = move_uploaded_file( $_FILES['myfile']['tmp_name'][$n], "{$dir}/{$name}" );
                $success = $success && $uploaded;
                if ( $success ) {
                    $flist[$name] = "{$url}/{$name}";
                }
            }

            if ( $success ) {
                $text = __('Files uploaded');
                exit( json_encode( array(
                    'info_text'  => $text,
                    'info_class' => 'info-success',
                    'info_time'  => 5000,
                    'flist'      => $flist,
                    'url'        => $url,
                ) ) );
            } else {
                exit( json_encode( array(
                    'info_text'  => $text,
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                    'url'        => $url,
                ) ) );
            }
            
        break;

    /* Создание поста */

        case 'save_post':
            
        /* Сгенерировать адрес если не передан в запросе */

            $time    = time();
            $updated = $time;
            $created = $time;

            //file_put_contents($soc['dir'].'/debug.txt', "\n".date('Y-m-d H:i:s')."\n", FILE_APPEND);

            $url = date( '/Y/m/d/H/i/', $time );
            if ( !empty( $_POST['url'] ) ) {
                /* Проверка URL */
                if ( !preg_match( '/(\d\d\d\d)\/(\d\d)\/(\d\d)\/(\d\d)\/(\d\d)\//', $_POST['url'], $m ) ) {
                    exit( json_encode( array(
                        'info_text'  => __('Bad URL.'),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
                $url = $_POST['url'];
                $created = strtotime( $m[1].'-'.$m[2].'-'.$m[3].' '.$m[4].':'.$m[5].':00' );
            }
            $dir = $soc['dir'].'/.posts'.$url;

            /* Для скрытия прочитанных и не интересных */
            $id  = sha1( $url . $time );
            
        /* Предотвратить перезапись если пост создается в ту же минуту */

            if ( is_dir( $dir ) && empty( $_POST['url'] ) ) {
                exit( json_encode( array(
                    'info_text'  => __('Please wait 1 min. Files were not uploaded.'),
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) );
            }

        /* Создание папки если не существует */

            if ( !is_dir( $dir ) && !mkdir( $dir, 0777, true ) ) {
                exit( json_encode( array(
                    'info_text'  => __('Can\'t create folder').' '.$dir,
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) );
            }

        /* Добавляем target=_blank если ссылки не локальные */

            $_POST['html'] = preg_replace_callback( '/<a ([^>]+)>/u', function($matches){
                if ( preg_match('/(http|https):\/\/([\w\-_\[:\]]+(\.[\w\-_]+)*)/u', $matches[1], $output_array) ) {

                    if ( $output_array[2] == $_SERVER['SERVER_NAME'] ) {
                        return $matches[0];
                    }

                    if ( preg_match('/target[ ]*=[ ]*["\']_blank["\']/u', $matches[0], $output_array) ) {
                        return $matches[0];
                    } else {
                        return "<a {$matches[1]} target=_blank>";
                    }

                } else {
                    /* Не найдено http|https */
                    return $matches[0];
                }
            }, $_POST['html'] );

        /* Создаем информационный файл */

            $json = array(
                'id'         => $id,
                'host'       => $_SERVER['SERVER_NAME'],
                'created'    => $created,
                'updated'    => $updated,
                'url'        => $url,
                'title'      => $_POST['title'],
                'html'       => $_POST['html'],
                'img'        => $_POST['img'],
                'public'     => $_POST['public'],
                'owner_node' => $_SERVER['SERVER_NAME'],
                'owner_name' => $config['name'],
            );
            
        /* Сохранение index.json */

            file_put_contents( "{$dir}/index.json", json_encode($json) );
            
        /* Опубликовано */

            exit( json_encode( array(
                'info_text'  => __('Saved'),
                'info_class' => 'info-success',
                'info_time'  => 1000,
                'result'     => 'ok',
                'url'        => $url,
            ) ) );
            
        break;

        /* Удаление поста, FIXME: удаление непубличного */

        case 'del':

            if ( preg_match( '/^\/\d\d\d\d\/\d\d\/\d\d\/\d\d\/\d\d\/$/', $_POST['url'] ) ) {

                $dir = $soc['dir'].'/.posts'.$_POST['url'];
                
                if ( is_dir( $dir ) && recurse_rm( $dir ) ) {
                    exit( json_encode( array(
                        'info_text'  => __("Deleted"),
                        'info_class' => 'info-success',
                        'info_time'  => 5000,
                        'result'     => 'deleted',
                    ) ) );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Can\'t delete'),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }

            }

        break;

        case 'hide':

            if ( file_exists( $soc['dir'].'/hidden.php' ) ) {
                include( $soc['dir'].'/hidden.php' );
            } else {
                $hidden = array();
            }

            $hidden[ $_POST['id'] ] = date( 'Y-m-d H:i:s' );
            $hidden = array_slice( $hidden, -1000 );

            @$r = file_put_contents( $soc['dir'].'/hidden.php', '<?php $hidden = '.var_export($hidden, true).";\n", LOCK_EX);

            if ( $r === false ) {
                exit( json_encode( array(
                    'info_text'  => __('Can\'t write hidden.php'),
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) ); 
            }

            exit( json_encode( array(
                'info_text'  => __("Hide"),
                'info_class' => 'info-success',
                'info_time'  => 5000,
                'result'     => 'hide',
            ) ) );

        break;

        case 'del_sess':

            unset( $config['logged'][$_POST['sess']] );
            soc_save_config();
            exit( json_encode( array(
                'info_text'  => __("Session closed"),
                'info_class' => 'info-success',
                'info_time'  => 5000,
                'result'     => 'ok',
            ) ) );

        break;

    }
}

/* Public API */

function public_api() {

    global $config, $soc;

    switch ( $_POST['fn'] ) {

        /* Вход или установка */

        case 'login':

            /* Вход */

            if ( !empty($config['login_url']) ) {
                if ( $_SERVER['HTTP_REFERER'] === $soc['url']['scheme'].'://'.$soc['url']['host'].$config['login_url'] ) {
                    
                    /* Заблокированные IP адреса */

                    if ( !empty($config['fail_login_ip']) && in_array( $_SERVER['REMOTE_ADDR'], $config['fail_login_ip'] ) ) {
                        exit;
                    }

                    if ( trim($_POST['password']) === $config['password'] ) {
                        
                        $d                     = date('Y-m-d H:i:s');
                        $login                 = sha1( $config['login_url'].$d );
                        $password              = sha1( $config['password'].$d );
                        $config['logged'][$login] = array(
                            'password' => $password,
                            'ip' => $_SERVER['REMOTE_ADDR'],
                            'date' => date('Y-m-d H:i:s'),
                        );

                        if ( soc_save_config() ) {

                            /* Вход выполнен */
                            
                            setcookie( 'soc_login',    $login,    0, $soc['base_url'] );
                            setcookie( 'soc_password', $password, 0, $soc['base_url'] );
                            exit( json_encode( array(
                                'goto' => $soc['base_url'],
                            ) ) );

                        } else {

                            exit( json_encode( array(
                                'info_text'  => __('Can\'t write config.php'),
                                'info_class' => 'info-error',
                                'info_time'  => 5000,
                            ) ) );
                        }
                    } else {
                        if ( empty($config['fail_login_ip']) ) { $config['fail_login_ip'] = array(); }
                        array_push( $config['fail_login_ip'], $_SERVER['REMOTE_ADDR'] );
                        soc_save_config();
                        exit;
                    }
                }
                exit;
            }

            /* Install */

            if ( empty( trim($_POST['login_url']) ) ) {
                exit( json_encode( array(
                    'info_text'  => __('Empty login url'),
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) );
            }

            $config['tpl']       = 'default';
            $config['login_url'] = $soc['base_url'].trim($_POST['login_url']);
            $config['password']  = trim($_POST['password']);
            $config['name']      = 'Noname';
            $d                = date('Y-m-d H:i:s');
            $login            = sha1( $config['login_url'].$d );
            $password         = sha1( $config['password'].$d );
            $config['logged'][$login] = array( 'password' => $password, 'ip' => $_SERVER['REMOTE_ADDR'] );
            
            if ( soc_save_config() ) {
                setcookie( 'soc_login',    $login,    0, $soc['base_url'] );
                setcookie( 'soc_password', $password, 0, $soc['base_url'] );
            } else {
                exit( json_encode( array(
                    'info_text'  => __('Can\'t write config.php'),
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) );
            }

            exit( json_encode( array(
                'result' => 'installed',
            ) ) );
        break;
    }
}



